package region

import (
	"context"
	"fast-boot/app/model"
	"github.com/hwUltra/fb-tools/gormx"
	"github.com/jinzhu/copier"

	"fast-boot/app/api/admin/internal/svc"
	"fast-boot/app/api/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type PageLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 菜单列表
func NewPageLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PageLogic {
	return &PageLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *PageLogic) Page(req *types.SysRegionPageReq) (resp []*types.SysRegionItem, err error) {
	//items := make([]*model.SysRegionModel, 0)
	//if err := l.svcCtx.GormClient.GormDb.Model(&model.SysRegionModel{}).
	//	Order("id asc").Find(&items).Error; err != nil {
	//	return nil, err
	//}
	items := (*model.SysRegionCache)(gormx.NewCacheTool(l.svcCtx.Config.Cache, l.svcCtx.GormClient.GormDb)).List()
	return GetRegionTree(items, 0), nil
}

func GetRegionTree(list []*model.SysRegionModel, parentCode int64) []*types.SysRegionItem {
	res := make([]*types.SysRegionItem, 0)
	for _, item := range list {
		if item.ParentCode == parentCode {
			var i types.SysRegionItem
			_ = copier.Copy(&i, item)
			i.Children = GetRegionTree(list, item.RegionCode)
			res = append(res, &i)
		}
	}
	return res
}
